#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2021/6/8
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :EC79_UnsettledRenew
# @Software  :PyCharm


'''eof
name:申请企业近5年信贷业务存在展期
code:EC79_UnsettledRenew
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

# reload(sys)
# sys.setdefaultencoding('utf-8')

# count（借贷账户信息单元(ED01)·特定交易信息段(ED01C)·特定交易信息(ED01CH)·交易类型(ED01CD01)=="11" 且交易日期（ED01CR01)在5年内的数据）
null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

# 借贷账户信息单元(ED01)·特定交易信息段(ED01C)·特定交易信息(ED01CH)·交易类型(ED01CD01)=="11" 的个数

def EC79_UnsettledRenew():
    data = EC_DSJ_2D.get('data')
    #EDA 借贷账户信息 [1..1]
    EDA = getTable(data, 'EDA', 1, 1)
    count = 0
    if EDA == [{}]:
        return '缺失值'
    elif EDA == 0:
        return 0
    else:
        #ED01 借贷账户信息单元 [0..*]
        ED01 = getTable(EDA[0], 'ED01', 0, 1)
        if ED01 == [{}]:
            return '缺失值'
        elif ED01 == 0:
            return 0
        else:
            for i in ED01:
                #ED01C 特定交易信息段 [0..1]
                ED01C = getTable(i, 'ED01C', 0, 0)
                if ED01C == [{}] or ED01C == 0:
                    pass
                else:
                    #ED01CH 特定交易信息 [0..*]
                    ED01CH = getTable(ED01C[0], 'ED01CH', 0, 1)
                    if ED01CH == [{}] or ED01CH == 0:
                        pass
                    else:
                        for i in ED01CH:
                            #ED01CD01 交易类型 [1..1]
                            ED01CD01 = i.get('ED01CD01')
                            #ED01CR01 交易日期 [1..1]
                            ED01CR01 = i.get('ED01CR01')
                            if ED01CD01 not in null_type_list and Formate(ED01CR01):
                                if ED01CD01 == '11' and float((datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m%d")) <= float(Formate(ED01CR01)) < float(datetime.datetime.now().strftime("%Y%m%d")):
                                    count += 1
    return count





result = EC79_UnsettledRenew()
# if __name__ == '__main__':
#     with open(r'C:\Users\john\Desktop\samples\EC_DSJ_2D.json',encoding='utf8') as ff:
#         EC_DSJ_2D = json.loads(ff.read())
#     result = EC79_UnsettledRenew()
#     print(result)